import { Request, Response, NextFunction, RequestHandler } from 'express';
import Stripe from 'stripe';
import { PaymentService } from '../services/PaymentService';
import { UserService } from '../services/UserService';
import { asyncHandler } from '../utils/asyncHandler';
import { stripe, STRIPE_WEBHOOK_SECRET } from '../config/stripe';

export class PaymentController {
  private paymentService: PaymentService;
  private userService: UserService;

  constructor() {
    this.paymentService = new PaymentService();
    this.userService = new UserService();
  }

  /**
   * 创建支付意图
   */
  createPaymentIntent: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { 
      amount, 
      currency = 'usd', 
      description, 
      metadata,
      allowRedirects = true,
      automaticPaymentMethods = true,
      paymentMethodTypes
    } = req.body;
    const userId = req.params.userId || req.body.userId;

    if (!userId) {
      return res.status(400).json({
        success: false,
        message: '用户ID是必需的',
      });
    }

    if (!amount || amount <= 0) {
      return res.status(400).json({
        success: false,
        message: '金额必须大于0',
      });
    }

    try {
      const result = await this.paymentService.createPaymentIntent({
        userId,
        amount,
        currency,
        description,
        metadata,
        allowRedirects,
        automaticPaymentMethods,
        paymentMethodTypes,
      });

      console.log('Payment Intent created with multiple payment methods support:', {
        paymentIntentId: result.paymentIntent.id,
        automaticPaymentMethods,
        allowRedirects,
        paymentMethodTypes: paymentMethodTypes || 'automatic'
      });

      return res.status(201).json({
        success: true,
        data: {
          paymentIntentId: result.paymentIntent.id,
          clientSecret: result.clientSecret,
          amount: result.paymentIntent.amount,
          currency: result.paymentIntent.currency,
          status: result.paymentIntent.status,
          allowRedirects,
        },
        message: '支付意图创建成功',
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        message: '创建支付意图失败',
        error: error.message,
      });
    }
  });

  /**
   * 确认支付
   */
  confirmPayment: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { paymentIntentId } = req.params;

    if (!paymentIntentId) {
      return res.status(400).json({
        success: false,
        message: '支付意图ID是必需的',
      });
    }

    try {
      const paymentIntent = await this.paymentService.confirmPayment(paymentIntentId);

      return res.json({
        success: true,
        data: {
          paymentIntentId: paymentIntent.id,
          status: paymentIntent.status,
          amount: paymentIntent.amount,
          currency: paymentIntent.currency,
        },
        message: '支付确认成功',
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        message: '确认支付失败',
        error: error.message,
      });
    }
  });

  /**
   * 使用支付方式确认支付（仅用于测试，生产环境不推荐）
   */
  confirmPaymentWithMethod: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { paymentIntentId } = req.params;
    const { paymentMethod } = req.body;

    if (!paymentIntentId) {
      return res.status(400).json({
        success: false,
        message: '支付意图ID是必需的',
      });
    }

    if (!paymentMethod || !paymentMethod.card) {
      return res.status(400).json({
        success: false,
        message: '支付方式信息是必需的',
      });
    }

    try {
      const paymentIntent = await this.paymentService.confirmPaymentWithMethod(
        paymentIntentId,
        paymentMethod
      );

      return res.json({
        success: true,
        data: {
          paymentIntentId: paymentIntent.id,
          status: paymentIntent.status,
          amount: paymentIntent.amount,
          currency: paymentIntent.currency,
        },
        message: '支付确认成功',
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        message: '确认支付失败',
        error: error.message,
      });
    }
  });

  /**
   * 获取支付意图
   */
  getPaymentIntent: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { paymentIntentId } = req.params;

    if (!paymentIntentId) {
      return res.status(400).json({
        success: false,
        message: '支付意图ID是必需的',
      });
    }

    try {
      const paymentIntent = await this.paymentService.getPaymentIntent(paymentIntentId);

      return res.json({
        success: true,
        data: {
          paymentIntentId: paymentIntent.id,
          status: paymentIntent.status,
          amount: paymentIntent.amount,
          currency: paymentIntent.currency,
          description: paymentIntent.description,
          created: paymentIntent.created,
        },
        message: '获取支付意图成功',
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        message: '获取支付意图失败',
        error: error.message,
      });
    }
  });

  /**
   * 取消支付
   */
  cancelPayment: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { paymentIntentId } = req.params;

    if (!paymentIntentId) {
      return res.status(400).json({
        success: false,
        message: '支付意图ID是必需的',
      });
    }

    try {
      const paymentIntent = await this.paymentService.cancelPayment(paymentIntentId);

      return res.json({
        success: true,
        data: {
          paymentIntentId: paymentIntent.id,
          status: paymentIntent.status,
        },
        message: '支付取消成功',
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        message: '取消支付失败',
        error: error.message,
      });
    }
  });

  /**
   * 获取用户支付历史
   */
  getUserPayments: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { userId } = req.params;
    const { limit = 10, offset = 0 } = req.query;

    if (!userId) {
      return res.status(400).json({
        success: false,
        message: '用户ID是必需的',
      });
    }

    try {
      const payments = await this.paymentService.getUserPayments(
        userId,
        parseInt(limit as string),
        parseInt(offset as string)
      );

      return res.json({
        success: true,
        data: payments,
        message: '获取支付历史成功',
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        message: '获取支付历史失败',
        error: error.message,
      });
    }
  });

  /**
   * 创建订阅
   */
  createSubscription: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { userId, priceId, trialPeriodDays, metadata } = req.body;

    if (!userId || !priceId) {
      return res.status(400).json({
        success: false,
        message: '用户ID和价格ID是必需的',
      });
    }

    try {
      const subscription = await this.paymentService.createSubscription({
        userId,
        priceId,
        trialPeriodDays,
        metadata,
      });

      return res.status(201).json({
        success: true,
        data: {
          subscriptionId: subscription.id,
          status: subscription.status,
          currentPeriodStart: (subscription as any).current_period_start,
          currentPeriodEnd: (subscription as any).current_period_end,
          trialStart: (subscription as any).trial_start,
          trialEnd: (subscription as any).trial_end,
          clientSecret: null,
        },
        message: '订阅创建成功',
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        message: '创建订阅失败',
        error: error.message,
      });
    }
  });

  /**
   * 取消订阅
   */
  cancelSubscription: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { subscriptionId } = req.params;
    const { cancelAtPeriodEnd = true } = req.body;

    if (!subscriptionId) {
      return res.status(400).json({
        success: false,
        message: '订阅ID是必需的',
      });
    }

    try {
      const subscription = await this.paymentService.cancelSubscription(
        subscriptionId,
        cancelAtPeriodEnd
      );

      return res.json({
        success: true,
        data: {
          subscriptionId: subscription.id,
          status: subscription.status,
          cancelAtPeriodEnd: subscription.cancel_at_period_end,
          canceledAt: subscription.canceled_at,
        },
        message: '订阅取消成功',
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        message: '取消订阅失败',
        error: error.message,
      });
    }
  });

  /**
   * 获取用户订阅
   */
  getUserSubscriptions: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { userId } = req.params;

    if (!userId) {
      return res.status(400).json({
        success: false,
        message: '用户ID是必需的',
      });
    }

    try {
      const subscriptions = await this.paymentService.getUserSubscriptions(userId);

      return res.json({
        success: true,
        data: subscriptions,
        message: '获取订阅列表成功',
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        message: '获取订阅列表失败',
        error: error.message,
      });
    }
  });

  /**
   * Stripe Webhook处理
   */
  handleWebhook: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const sig = req.headers['stripe-signature'] as string;
    const rawBody = req.body;

    if (!STRIPE_WEBHOOK_SECRET) {
      return res.status(500).json({
        success: false,
        message: 'Webhook密钥未配置',
      });
    }

    try {
      // 验证webhook签名
      const event = stripe.webhooks.constructEvent(
        rawBody,
        sig,
        STRIPE_WEBHOOK_SECRET
      );

      // 处理事件
      await this.paymentService.handleWebhookEvent(event);

      return res.json({ received: true });
    } catch (error: any) {
      console.error('Webhook签名验证失败:', error.message);
      return res.status(400).json({
        success: false,
        message: 'Webhook签名验证失败',
        error: error.message,
      });
    }
  });

  /**
   * 获取Stripe公钥
   */
  getPublishableKey: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const publishableKey = process.env.STRIPE_PUBLISHABLE_KEY;
    
    if (!publishableKey) {
      return res.status(500).json({
        success: false,
        message: 'Stripe公钥未配置',
      });
    }

    return res.json({
      success: true,
      data: {
        publishableKey,
      },
      message: '获取公钥成功',
    });
  });

  /**
   * 创建 Checkout Session
   */
  createCheckoutSession: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    // ... existing code ...
  });
}